package com.ym.controller.patient.askDoctor;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ym.common.constant.Constants;
import com.ym.common.utils.page.PageDomain;
import com.ym.core.annotation.ApiSign;
import com.ym.core.annotation.Log;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.domain.entity.InquiryOrderContentEntity;
import com.ym.medical.domain.entity.InquiryOrderEntity;
import com.ym.medical.domain.entity.PatientDetailEntity;
import com.ym.medical.domain.param.InquiryOrderParam;
import com.ym.medical.domain.param.OrderParam;
import com.ym.medical.domain.param.PatientDetailParam;
import com.ym.medical.domain.vo.ConsultSummaryVo;
import com.ym.medical.domain.vo.InquiryOrderContentVo;
import com.ym.medical.domain.vo.ResultDoctor;
import com.ym.medical.enums.PatientDetailRelationEnum;
import com.ym.medical.service.IConsultSummarySV;
import com.ym.medical.service.IInquiryOrderSV;
import com.ym.medical.service.IOrderPaySV;
import com.ym.medical.service.IPatientDetailSV;
import com.ym.medical.service.impl.InquiryOrderContentSVImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dai
 * @create 2019-05-06 14:47
 **/
@Api(tags = "患者端-首页-快速问诊")
@RestController
@ApiSign
@RequestMapping(value = "/patient/ask/inquiry",headers= Constants.Api.VERSION)
@Validated
public class InquiryController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(InquiryController.class);

	@Autowired
	private IPatientDetailSV patientDetailSV;

	@Autowired
	private IConsultSummarySV consultSummarySV;

	@Autowired
	private InquiryOrderContentSVImpl inquiryOrderContentSV;

	@Autowired
	private IOrderPaySV orderPaySV;

	@Autowired
	private IInquiryOrderSV inquiryOrderSV;


	@ApiOperation("问诊人列表展示")
	@GetMapping(value = "/list")
	public APIResponse<PageInfo<PatientDetailEntity>> listPage(@RequestParam(defaultValue = "1", required = false) int pageNum, @RequestParam(defaultValue = "5", required = false) int pageSize) {
		Long userId = ShiroUtil.getLoginId();
		PageDomain.startPage(pageNum,pageSize);
		List<PatientDetailEntity> patientDetailEntities = patientDetailSV.selectList(
				TK.select(PatientDetailEntity.class).where()
						.andEqualTo(PatientDetailEntity::getUserId, userId)
						.end()
						.orderByClause("case when user_id=" + userId + " then 1 else 2 end,create_time desc")
		);
		return successPage(patientDetailEntities);
	}

	@Log
	@ApiOperation("新增问诊人")
	@PostMapping(value = "/patient/insert")
	public APIResponse<PatientDetailEntity> insertPatient(@RequestBody PatientDetailEntity patientDetail) {
		Long userId = ShiroUtil.getLoginId();
		patientDetail.setUserId(userId);
		String patientName = patientDetail.getName();
		String idNo = patientDetail.getIdNo();
		String relation = patientDetail.getRelation();
		List<PatientDetailEntity> patientDetails = patientDetailSV.selectList(PatientDetailParam.builder().userId(userId).build().covert());
		if (!patientDetails.isEmpty()) {
			for (PatientDetailEntity detail : patientDetails) {
				if (patientName.equals(detail.getName())) {
					return failMsg("该患者的姓名已经存在!");
				}
				if (idNo.equals(detail.getIdNo())) {
					return failMsg("该患者的身份证号已经存在!");
				}
				if (relation.equals(PatientDetailRelationEnum.I_AM.getKey())) {
					return failMsg("您已经添加过自己了!");
				}
			}
		}
		patientDetailSV.insert(patientDetail);
		return successData(patientDetail);
	}

	@ApiOperation("咨询总结查看页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "咨询室id", required = true, paramType = "query", dataType = "Long")
	})
	@GetMapping(value = "/selectSummaryByCourId")
	public APIResponse<ConsultSummaryVo> selectSummaryByCourId(@RequestParam Long id) {
		ConsultSummaryVo consultSummary = consultSummarySV.selectSummaryByCourId(id);
		return successData(consultSummary);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("问诊更多描述查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "订单ID", required = true, paramType = "form")
	})
	@GetMapping(value = "/after/ask/list")
	public APIResponse<List<InquiryOrderContentVo>> afterAskList(
			Long orderId
	) {
		List<InquiryOrderContentVo> inquiryOrderContents = inquiryOrderContentSV.listContent(orderId);
		return successData(inquiryOrderContents);
	}

	@ApiOperation("问诊更多描述添加")
	@PostMapping(value = "/after/ask")
	public APIResponse askForMoreDescriptionsToAdd(InquiryOrderContentEntity content
	) {
		content.setCreateTime(new Date());
		content.setCraetePerson(ShiroUtil.getLoginId());
		inquiryOrderContentSV.insert(content);
		return success();
	}


	@ApiOperation("退费并推荐其他医生")
	@PostMapping(value = "/refund/recommendOtherDoctors", consumes = MediaType.APPLICATION_JSON_VALUE)
	public APIResponse<List<ResultDoctor>> refundAndrecommendOtherDoctors(
			@RequestBody OrderParam orderModel,
			HttpServletRequest request
	) {
		List<ResultDoctor> result = new ArrayList<>();
		String serviceUrl = request.getRequestURL().toString().replaceAll("/patient/ask/inquiry/return/recommendOtherDoctors", "/patient/order/orderRefundCallback");
		orderModel.setCallbackUrl(serviceUrl);
		JSONObject jsonObject = orderPaySV.refundOrder(orderModel);
		if (jsonObject != null) {
			//表示退费发起成功。开始推荐医生
			InquiryOrderEntity byModel = inquiryOrderSV.findByModel(InquiryOrderParam.builder().ioNum(orderModel.getOutTradeNo()).build());
			result = inquiryOrderSV.recommendOtherDoctors(byModel.getId());
		}
		return successData(result);
	}

	@ApiOperation("推荐医生列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderId", value = "订单ID", required = true, paramType = "form")
	})
	@PostMapping(value = "/recommendedDoctorList", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public APIResponse<List<ResultDoctor>> recommendOtherDoctors(
			Long orderId
	) {
		List<ResultDoctor> result = inquiryOrderSV.recommendOtherDoctors(orderId);
		return successData(result);
	}

	@ApiOperation("举报订单重新修改提交")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderId", value = "订单ID", required = true, paramType = "form"),
			@ApiImplicitParam(name = "attach", value = "附件", required = false, paramType = "form"),
			@ApiImplicitParam(name = "content", value = "订单内容", required = true, paramType = "form")
	})
	@PostMapping(value = "/order/revision", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public APIResponse orderRevision(
			@NotNull Long orderId,
			String attach,
			@NotEmpty String content
	) {
		inquiryOrderSV.orderRevision(orderId, attach, content);
		return success();
	}
}
